package com.hys.authserver.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.RegisteredPayload;
import lombok.extern.slf4j.Slf4j;

import java.time.ZoneId;
import java.util.Date;

/**
 * IDE: IntelliJ IDEA
 * 项目: auth-server
 * 日期: 2024/9/19 1:00:04
 * 作者: qscy
 * 功能:
 **/
@Slf4j
public class JwtUtils {

    private static final byte[] key = "123123dsadas213da32sd3124234sadfd".getBytes();

    public static String createToken(String uuid, String username, String phone, String uid, String roles) {
        Date signTime = new Date();
        Date expireTime = DateTime.of(LocalDateTimeUtil
                .of(signTime)
                .plusSeconds(RedisUtils.JWT_TOKEN_EXPIRE_TIME)
                .atZone(ZoneId.systemDefault())
                .toInstant()
                .toEpochMilli());

        return JWT.create()
                .setJWTId(uuid)
                .setIssuedAt(signTime)
                .setExpiresAt(expireTime)
                .setSubject(username)
                .setAudience("jkfw")
                .setNotBefore(signTime)
                .setIssuer("auth-server")
                .setPayload("uid", uid)
                .setPayload("username", username)
                .setPayload("phone", phone)
                .setPayload("roles", roles)
                .setSigner("HS256", key)
                .sign();
    }

    public static boolean validateToken(String token) {
        try {
            if (JWTUtil.verify(token, key)) {
//                long expire = Long.parseLong(JWTUtil.parseToken(token).getPayload(RegisteredPayload.EXPIRES_AT).toString()) * 1000;
//                if (expire > System.currentTimeMillis()) {
//                    return true;
//                }
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    public static String id(String token) {
        return JWTUtil.parseToken(token).getPayload(RegisteredPayload.JWT_ID).toString();
    }

    public static String username(String token) {
        return JWTUtil.parseToken(token).getPayload("username").toString();
    }

    public static String phone(String token) {
        return JWTUtil.parseToken(token).getPayload("phone").toString();
    }

    public static void main(String[] args) {
        String token = JwtUtils.createToken("admin", "1","phone", "2", "admin");
        log.info("token:{}", token);

        boolean b = JwtUtils.validateToken(token);
        log.info("b:{}", b);
    }
}
